﻿using FreeImageAPI;
using System;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Converter
{
	public class ConverterAPI
	{
		/// <summary>
		/// 时间戳转为C#格式时间	<see cref="http://www.cnblogs.com/yc-755909659/archive/2012/12/25/2832673.html"/>
		/// </summary>
		/// <param name="timeStamp">Unix时间戳格式</param>
		/// <returns>C#时间格式</returns>
		public static DateTime GetTime(string timeStamp)
		{
			DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
			long time = new long();
			try
			{
				time = long.Parse(timeStamp + "0000000");
			}
			catch (System.OverflowException e)
			{

				System.Windows.MessageBox.Show(e.Message + "\nInt64最大值为" + Convert.ToString(Int64.MaxValue));
			}
			TimeSpan toNow = new TimeSpan(time);
			return dtStart.Add(toNow);
		}

		/// <summary>
		/// DateTime时间格式转换为Unix时间戳	<see cref="http://www.cnblogs.com/yc-755909659/archive/2012/12/25/2832673.html"/>
		/// </summary>
		/// <param name="time">DateTime时间格式</param>
		/// <returns>Unix时间戳</returns>
		public static int ConverDateTimeInt(System.DateTime time)
		{
			System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
			return (int)(time - startTime).TotalSeconds;
		}
	}


	/// <summary>
	/// 自定义时间转换为	<see cref="http://www.cnblogs.com/tianma3798/p/5927470.html"/>
	/// </summary>
	public class TimeConver : IValueConverter
	{
		//当值从绑定源传播到目标时，调用方法Convert
		public object Convert(object value, Type targetType, object paramer, CultureInfo culture)
		{
			if (value == null)
			{
				return DependencyProperty.UnsetValue;
			}
			string valueString = value as string;
			DateTime dt = ConverterAPI.GetTime(valueString);
			return dt;
		}

		//当值从绑定目标传播给绑定源时，调用ConvertBack
		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (value == null)
			{
				return DependencyProperty.UnsetValue;
			}

			DateTime dt = (DateTime)value;
			return ConverterAPI.ConverDateTimeInt(dt);
		}
	}

	/// <summary>
	/// bool 与 Visibility之间的转换	<see cref="http://blog.csdn.net/yapingxin/article/details/9792637"/>
	/// </summary>
	[ValueConversion(typeof(bool), typeof(Visibility))]
	public class VisibilityConverter : IValueConverter
	{
		/// <summary>
		/// 当值从绑定源传播到目标时，调用方法Convert
		/// </summary>
		/// <param name="value"></param>
		/// <param name="targetType"></param>
		/// <param name="parameter"></param>
		/// <param name="culture"></param>
		/// <returns></returns>
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if ((bool)value)
			{
				return Visibility.Visible;
			}
			else
			{
				return Visibility.Collapsed;
			}
		}

		/// <summary>
		/// 当值从绑定目标传播给绑定源时，调用ConvertBack
		/// </summary>
		/// <param name="value"></param>
		/// <param name="targetType"></param>
		/// <param name="parameter"></param>
		/// <param name="culture"></param>
		/// <returns></returns>
		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			return (Visibility)value == Visibility.Visible;
		}
	}

	/// <summary>
	/// byte[]数组与string 之间转换(default)
	/// </summary>
	[ValueConversion(typeof(byte[]), typeof(string))]
	public class ByteArryConverter : IValueConverter
	{
		/// <summary>
		/// 当值从绑定源传播到目标时，调用方法Convert
		/// </summary>
		/// <param name="value"></param>
		/// <param name="targetType"></param>
		/// <param name="parameter"></param>
		/// <param name="culture"></param>
		/// <returns></returns>
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			return System.Text.Encoding.Default.GetString((byte[])value).TrimEnd('\0');
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			try
			{
				return System.Text.Encoding.Default.GetBytes((string)value);
			}
			catch (Exception e)
			{

				throw (e);
			}

			//return new byte();
		}
	}

	/// <summary>
	/// byte[]数组与string之间转换（Unicode） 
	/// </summary>
	[ValueConversion(typeof(byte[]), typeof(string))]
	public class UByteArryConverter : IValueConverter
	{
		object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			return System.Text.Encoding.Unicode.GetString((byte[])value).TrimEnd('\0');
		}

		object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			try
			{
				return System.Text.Encoding.Unicode.GetBytes((string)value);
			}
			catch (Exception e)
			{

				throw (e);
			}
		}
	}

	/// <summary>
	/// Char[]数组与string 之间转换
	/// </summary>
	[ValueConversion(typeof(byte[]), typeof(string))]
	public class CharArryConverter : IValueConverter
	{
		/// <summary>
		/// 当值从绑定源传播到目标时，调用方法Convert
		/// </summary>
		/// <param name="value"></param>
		/// <param name="targetType"></param>
		/// <param name="parameter"></param>
		/// <param name="culture"></param>
		/// <returns></returns>
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (value == null)
			{
				return "";
			}
			return new string((char[])value).TrimEnd('\0');
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if(value == null)
			{
				return new char();
			}
			var valueStr=value as string;
			return valueStr.ToCharArray();
		}
	}

	/// <summary>
	/// DDS图片格式转换器
	/// </summary>
	public class DDSConverter : IValueConverter
	{
		private static readonly DDSConverter defaultInstance = new DDSConverter();

		public static DDSConverter Default
		{
			get
			{
				return DDSConverter.defaultInstance;
			}
		}


		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (value == null)
			{
				throw new ArgumentException("value");
			}
			else if (value is string)
			{
				return DDSConverter.Convert((string)value);
			}
			else
			{
				throw new NotSupportedException(string.Format("{0} connot convert from {1}.", this.GetType(), value.GetType().FullName));
			}
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotSupportedException(string.Format("{0} does not support converting back.", this.GetType().FullName));
		}

		public static ImageSource Convert(string filePath)
		{
			if (!File.Exists(filePath))
			{
				return new BitmapImage();
			}

			FreeImageAPI.FIBITMAP fiBitmap = FreeImage.LoadEx(filePath);
			MemoryStream btStream = new MemoryStream();
			bool isSucceed = FreeImage.SaveToStream(fiBitmap, btStream, FREE_IMAGE_FORMAT.FIF_PNG);
			BitmapImage bi = new BitmapImage();
			bi.BeginInit();
			bi.StreamSource = btStream;
			bi.EndInit();

			return bi;
		}

	}
}
